package com.changgou.search.controller;


import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.Searchservice;
import org.springframework.beans.factory.annotation.Autowired;

import com.changgou.entity.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/search")
public class SearchController {


    @Autowired
    private Searchservice searchservice;


    @GetMapping
    @ResponseBody
    public Map search(@RequestParam Map<String, String> searchMap) {

        // 特殊符号的处理
        this.handleSearchMap(searchMap);

        Map map = searchservice.search(searchMap);

        return map;
    }


    @GetMapping("/list")
    public String list(@RequestParam Map<String, String> searchMap, Model model) {

        this.handleSearchMap(searchMap);

        Map map = searchservice.search(searchMap);
        model.addAttribute("result",map);
        model.addAttribute("searchMap",searchMap);

        //封装分页数据并返回
        //1.总记录数
        //2.当前页
        //3.每页显示多少条
        Page<SkuInfo> page = new Page<SkuInfo>(
                Long.parseLong(String.valueOf( map.get("total"))),
                Integer.parseInt(String.valueOf(map.get("pageNum"))),
                Page.pageSize
        );
        model.addAttribute("page",page);






        // 拼url
        StringBuilder url = new StringBuilder("/search/list");

        if (CollectionUtils.isEmpty(map)){
            url.append("?");
            for (String paramKey : searchMap.keySet()) {
                if (!"sortRule".equals(paramKey) && !"sortField".equals(paramKey) && !"pageNum".equals(paramKey)){

                    url.append(paramKey+"="+searchMap.get(paramKey)+"&");
                }
            }

            String substring = url.substring(0, url.lastIndexOf("&") - 1);
            model.addAttribute("url",substring);

        }else {
            model.addAttribute("url",url);
        }






        return "search";
    }


    private void handleSearchMap(Map<String, String> searchMap) {

        Set<Map.Entry<String, String>> set = searchMap.entrySet();
        for (Map.Entry<String, String> entry : set) {
            if (entry.getKey().startsWith("spec_")) {
                searchMap.put(entry.getKey(), entry.getValue().replace("+", "%2B"));

            }
        }
    }


}
